// 数据库操作
const mongoose = require('mongoose');
// 对象规则验证
const Joi = require('joi');
// 模型规则类
const {
    Schema
} = mongoose;

// 订单模型规则
const orderSchema = new Schema({
    // 订单日期
    orderDate: {
        type: Date,
        required: [true, '订单日期不能为空']
    },
    // 房间
    room: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Room',
        require: true
    },
    // 预订单号
    orderRef: {
        type: String,
        min: 5,
        max: 40
    },
    customers: {
        type: Array,
        default: []
    },
    isValid: {
        type: Boolean,
        required: true,
        default: false
    },
    createTime: {
        type: Boolean,
        required: true,
        default: new Date(),
    },
    // 单元格内容
    cell: {
        type: String
    },
    // 批注内容
    comment: {
        type: String
    }
}, {
    versionKey: false
});

/* orderSchema.index({
    orderDate: 1
}, {
    room: 1
}, {
    isValid: 1
}); */

const Order = mongoose.model('Order', orderSchema);

// 订单格式校验
const validateRev = order => {
    // 定义对象验证规则
    const schema = {
        orderDate: Joi.date(),
        room: Joi.string().required().regex(/^[0-9a-fA-F]{24}$/).error(new Error('房间ID非法')),
        orderRef: Joi.string().min(5).max(40).required().error(new Error('预订单号不符合验证验证规则'))
    };
    // 验证
    return Joi.validate(order, schema, {
        // 检测到所有错误
        abortEarly: false,
        // 允许对象包含被忽略的未知键
        allowUnknown: true
    });
}

const getOrders = async (date, tag) => {
    const config = {};
    if (date) config.orderDate = date;
    if (tag) config.tag = tag;
    const orders = await Order.find(config);
    return orders;
}

const getAllOrders = async () => {
    return await Order.findAll();
}

// 导出模块成员
module.exports = {
    Order,
    getOrders,
    getAllOrders
}